package com.pan.tools;

import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;

@Component
public class ObjectToMap {

    public static <T> Map<String,Object> parameterToMap(T obj){
        Class clazz = obj.getClass();
        Map map = new HashMap();
        Field[] fields = clazz.getDeclaredFields();
        Consumer<Field> putMap = field -> {
            field.setAccessible(true);
            try {
                map.put(field.getName(),field.get(obj));
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        };
        Arrays.stream(fields).forEach(putMap);
        return map;
    }
    public static Map<String,Object> toMap(Object obj){
        Map<String,Object> map = new HashMap<>();
        Field[] fields = obj.getClass().getDeclaredFields();
        Arrays.stream(fields).forEach(field -> {
            String memberName = field.getName();
            String firstUpMember = memberName.substring(0,1).toUpperCase()+memberName.substring(1);
            String getMethodName = "get"+firstUpMember;
            Object value ;
            try {
                Method method = obj.getClass().getMethod(getMethodName);
                value = method.invoke(obj);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            map.put(memberName,String.valueOf(value));
        });
        return map;
    }
}
